﻿using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace System.Timers
{
    /// <inheritdoc cref="ITimerService{TServiceBody}"/>
    /// <typeparam name="TServiceBody"><inheritdoc cref="ITimerServiceBody" path="/summary"/></typeparam>
    public class TimerService<TServiceBody> : ITimerService<TServiceBody>, IHostedService
        where TServiceBody : ITimerServiceBody, new()
    {
        private readonly System.Timers.Timer _timer;
        private readonly TServiceBody _serviceBody;
        private readonly int _delay;

        /// <inheritdoc/>
        public double Interval { get; }

        /// <inheritdoc cref="TimerService{TServiceBody}"/>
        /// <param name="interval">循环周期，若小于等于0，则只执行一次</param>
        /// <param name="delay">延迟启动的时间，值小于等于0时，为立即启动，单位：毫秒</param>
        public TimerService(double interval, int delay = 0)
        {
            Interval = interval;
            _delay = delay;

            System.Timers.Timer timer = new System.Timers.Timer(interval);
            timer.Elapsed += Timer_Elapsed;
            timer.AutoReset = interval > 0;
            _timer = timer;

            _serviceBody = new TServiceBody();
        }

        private async void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            await _serviceBody.ExecuteAsync();
            await Task.CompletedTask;
        }

        /// <inheritdoc/>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (_delay > 0)
            {
                await Task.Delay(_delay);
            }

            _timer.Start();
            await Task.CompletedTask;
        }

        /// <inheritdoc/>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _timer.Stop();
            await Task.CompletedTask;
        }
    }
}
